package com.jt.www.config.serializer;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * 对象序列化器接口
 */
public interface ObjectSerializer {

    <T> byte[] serialize(T object);

    <T> T deserialize(byte[] input, Class<T> clazz);

    default Object deserializeObject(byte[] input) {
        Object objectValue = null;
        ByteArrayInputStream byteArrayInputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            if (input != null) {
                byteArrayInputStream = new ByteArrayInputStream(input);
                objectInputStream = new ObjectInputStream(byteArrayInputStream);
                objectValue = objectInputStream.readObject();
            }
        } catch (IOException e) {
            throw new IllegalArgumentException("执行二进制反序列化操作失败", e);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("执行二进制反序列化操作失败", e);
        } finally {
            if (byteArrayInputStream != null) {
                try {
                    byteArrayInputStream.close();
                } catch (IOException e) {
                    throw new IllegalArgumentException(e);
                }
            }
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    throw new IllegalArgumentException(e);
                }
            }
        }
        return objectValue;
    }

}